package com.xunshibao.tutor.user.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xunshibao.core.security.Security;
import com.xunshibao.core.utils.JsonUtil;
import com.xunshibao.core.web.SessionUser;
import com.xunshibao.tutor.common.SchoolServiceImpl;
import com.xunshibao.tutor.po.School;
import com.xunshibao.tutor.po.Tutor;
import com.xunshibao.tutor.user.service.TutorServiceImpl;

@Controller
@RequestMapping(value = "/mem/*")
public class MemberController implements ResourceLoaderAware {
	@Autowired
	private TutorServiceImpl tutorService;
	@Autowired
	private SchoolServiceImpl schoolService;
	
    private File avatorDir = null;
    public void setResourceLoader(ResourceLoader resourceLoader) {
        try {
            avatorDir = resourceLoader.getResource("avator").getFile();
        } catch (Exception e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
        }
    }
    
    @RequestMapping(value = "photo")
    public String photo(HttpServletRequest request, Model model) {
    	String sessionId = request.getSession().getId();
    	model.addAttribute("sessionId", sessionId);
        return "mem/photo";
    }
    
    @RequestMapping(value = "index.php")
    public @ResponseBody String photo(HttpServletRequest request, @RequestParam(value = "avatar1", required=false) String avatar1, @RequestParam(value = "avatar2", required=false) String avatar2,
            @RequestParam(value = "avatar3", required=false) String avatar3, @RequestParam(value="Upload", required=false) File file) {
        File photo1 = new File(avatorDir, "1.jpg");
        File photo2 = new File(avatorDir, "2.jpg");
        File photo3 = new File(avatorDir, "3.jpg");
        
        try {
            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(photo1));
            flashdecode(avatar1, fos);
            fos.close();
            
            fos = new BufferedOutputStream(new FileOutputStream(photo2));
            flashdecode(avatar2, fos);
            fos.close();
            
            fos = new BufferedOutputStream(new FileOutputStream(photo3));
            flashdecode(avatar3, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "<root><message type=\"error\" value=\"-2\" /></root>";
        } 
        
        return "<?xml version=\"1.0\" ?><root><face success=\"1\"/></root>";
    }
    
    private boolean flashdecode(String value, BufferedOutputStream fos) {
        char[] chars = value.toCharArray();
        int k1;
        int k2;
        try {
            for (int i = 0, j = 0; i < chars.length; i = i + 2, j++) {
                k1 = chars[i] - 48;
                k1 -= (k1 > 9) ? 7 : 0;
                k2 = chars[i + 1] - 48;
                k2 -= (k2 > 9) ? 7 : 0;
                fos.write((k1 << 4 | k2));
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    
    @RequestMapping(value="profile", method=RequestMethod.GET)
    @Security
    public String profile(SessionUser user, Model model) {
    	Long userId = user.getUserId();
    	Tutor tutor = tutorService.getTutor(userId);
    	if(tutor == null) {
    		model.addAttribute("status", 0);//没有登记过
    	} else {
    		model.addAttribute("status", 1);
    		if(tutor.getSchool() != null) {
    			School school = schoolService.gettUiversity(tutor.getSchool());
    			model.addAttribute("schoolName", school.getName());
    		}
    		model.addAttribute("model", JsonUtil.toJson(tutor));
    	}
    	return "mem/profile";
    }
    
    @RequestMapping(value="profile", method=RequestMethod.POST)
    @Security
    public @ResponseBody Map<String, Object> profile(Tutor tutor, SessionUser user) {
    	Map<String, Object> json = new HashMap<String, Object>();
    	int result = tutorService.save(tutor, user.getUserId());
    	json.put("status", result);
    	return json;
    }
    
    @RequestMapping(value="changepwd", method=RequestMethod.GET)
    public String changepwd() {
    	return "mem/changepwd";
    }
    
    @RequestMapping(value="changepwd", method=RequestMethod.POST)
    public String changepwd(@RequestParam(value="newpwd")String newpwd, @RequestParam(value="pwd")String oldpwd) {
    	return "mem/changepwd";
    }
}
